package com.wyq.service.impl;

import com.wyq.domain.LoginUser;
import com.wyq.domain.ResponseResult;
import com.wyq.domain.User;
import com.wyq.service.LoginService;
import com.wyq.utils.JwtUtil;
import com.wyq.utils.RedisCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Objects;

@Service
public class LoginServiceImpl implements LoginService {

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private RedisCache redisCache;

    @Override
    public ResponseResult login(User user) {
        //AuthenticationManager 进行用户认证
        UsernamePasswordAuthenticationToken upat = new UsernamePasswordAuthenticationToken(user.getUserName(),
                                                                                            user.getPassword());
        Authentication authenticate = authenticationManager.authenticate(upat);
        //如果认证没通过，给出对应的提示
        if(Objects.isNull(authenticate)){
            throw new RuntimeException("登录失败");
        }
        //通过认证后，用userid生成jwt
        LoginUser loginUser = (LoginUser)authenticate.getPrincipal();
        String jwt = JwtUtil.createJWT(loginUser.getUser().getId().toString());
        HashMap<String,String> map = new HashMap<String, String>();
        map.put("token", jwt);

        redisCache.setCacheObject("login:"+loginUser.getUser().getId(),loginUser);
        return new ResponseResult(200,"登录成功",map);
    }

    @Override
    public ResponseResult logout() {
        //获取SecurityContextHolder中的用户id
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();

        //删除redis中的用户id
        String key = "login:"+loginUser.getUser().getId();
        redisCache.deleteObject(key);
        return new ResponseResult(200,"注销成功");
    }
}
